package hn.sigit.interop.dbf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashSet;
import java.util.Set;

import org.geotools.data.shapefile.dbf.DbaseFileHeader;
import org.geotools.data.shapefile.dbf.DbaseFileWriter;

public abstract class DBF {
	public static final int INT_LENGTH = 10;
	public static final int LONG_LENGTH = 19;
	public static final int LOGICAL_LENGTH = 1;
	public static final int DATE_LENGTH = 8;
	
	private final File file;
	private FileOutputStream fos;
	private int numRecords;
	private DbaseFileHeader dbfHeader;
	private DbaseFileWriter dbfWriter;
	private Set<Long> keySet;
	
	
	public DBF(File file) {
		this.file = file;
		dbfHeader = new DbaseFileHeader();
		numRecords = 0;
	}
	
	public File getFile() {
		return file;
	}
	
	public void open() throws IOException {
		fos = new FileOutputStream(file);
		dbfWriter = new DbaseFileWriter(dbfHeader, fos.getChannel());
	}
	
	protected void addRecord(Object[] record) throws IOException {
		dbfWriter.write(record);
		numRecords++;
	}
	
	protected void addUniqueRecord(Long key, Object[] record) throws IOException {
		if (keySet == null)
			keySet = new HashSet<Long>();
		
		if (keySet.contains(key)) return;
		
		dbfWriter.write(record);
		numRecords++;
		
		keySet.add(key);
	}
	
	public void close() throws IOException {
		if (dbfWriter != null) dbfWriter.close();
		if (fos != null) fos.close();
		
		RandomAccessFile raf = new RandomAccessFile(file, "rwd");
		raf.seek(0L);
		dbfHeader.setNumRecords(numRecords);
		dbfHeader.writeHeader(raf.getChannel());
		raf.close();
		
		numRecords = 0;
		dbfHeader.setNumRecords(0);
	}


	public DbaseFileHeader getDbfHeader() {
		return dbfHeader;
	}
}
